﻿using RimWorld;
using Verse;
using System.Collections.Generic;
using System.Linq;
using Verse.AI.Group;
using static RimZombieGirl.IncidentWorker_CursedGraveSpawn;

namespace RimZombieGirl
{
    public class LootEntry
    {
        public ThingDef thingDef;
        public IntRange countRange = new IntRange(1, 1);
    }

    public class CompProperties_CursedGrave : CompProperties
    {
        public List<LootEntry> lootTable;   // 物品+数量范围
        public List<string> enemyDefs;      // 可能出现的敌人 DefName 列表
        public int curseValue = 10;         // 挖掘增加的诅咒值
        public int minLoot = 1;             // 最少掉几类
        public int maxLoot = 3;             // 最多掉几类
        public float enemySpawnChance = 0.25f; // 25% 概率挖出敌人
        public IntRange enemySpawnCount = new IntRange(1, 3); // 一次能刷出的敌人数目范围
        public float darknessTriggerChance = 0.2f; // 触发黑暗的概率

        public CompProperties_CursedGrave()
        {
            this.compClass = typeof(CompCursedGrave);
        }
    }

    public class CompCursedGrave : ThingComp
    {
        public CompProperties_CursedGrave Props => (CompProperties_CursedGrave)props;

        public void DigUp()
        {
            Map map = parent.Map;
            IntVec3 pos = parent.Position;

            List<Pawn> spawnedEnemies = null;

            if (!Props.enemyDefs.NullOrEmpty() && Rand.Chance(Props.enemySpawnChance))
            {
                int enemyCount = Props.enemySpawnCount.RandomInRange;
                spawnedEnemies = new List<Pawn>();

                for (int i = 0; i < enemyCount; i++)
                {
                    string pawnDefName = Props.enemyDefs.RandomElement();
                    PawnKindDef kindDef = DefDatabase<PawnKindDef>.GetNamedSilentFail(pawnDefName);

                    if (kindDef != null)
                    {
                        Pawn enemy = PawnGenerator.GeneratePawn(kindDef, Faction.OfAncientsHostile);
                        GenSpawn.Spawn(enemy, pos, map, WipeMode.Vanish);
                        spawnedEnemies.Add(enemy);
                    }
                }

                if (spawnedEnemies.Any())
                {
                    // 给所有敌人分配同一个 Lord
                    LordMaker.MakeNewLord(
                        Faction.OfAncientsHostile,
                        new LordJob_AssaultColony(Faction.OfAncientsHostile, canKidnap: false, canTimeoutOrFlee: false),
                        map,
                        spawnedEnemies
                    );

                    Messages.Message("Some restless souls crawled out of the grave!".Translate(),
                    spawnedEnemies.First(), MessageTypeDefOf.ThreatSmall);
                    SoundDefOfHelper.PlaySoundOnce("GraveZombieSpawn_Sound", pos, map);

                    // 有概率触发 GameCondition_UnnaturalDarkness
                    if (Rand.Chance(Props.darknessTriggerChance))
                    {                        
                        if (map.gameConditionManager.ActiveConditions.Any(cond => cond.def == GameConditionDefOf.UnnaturalDarkness))
                        {
                            GameCondition newCond = GameConditionMaker.MakeCondition(GameConditionDefOf.UnnaturalDarkness, 60000); // 持续1天(60000 ticks)
                            map.gameConditionManager.RegisterCondition(newCond);
                            Messages.Message("The grave's darkness spreads...".Translate(), MessageTypeDefOf.ThreatBig);
                        }
                    }
                }
            }
            else
            {
                if (!Props.lootTable.NullOrEmpty())
                {
                    int lootEntries = Rand.RangeInclusive(Props.minLoot, Props.maxLoot);
                    List<LootEntry> availableLoot = Props.lootTable.InRandomOrder().Take(lootEntries).ToList();

                    foreach (LootEntry entry in availableLoot)
                    {
                        int stackCount = entry.countRange.RandomInRange;
                        Thing thing = ThingMaker.MakeThing(entry.thingDef);
                        thing.stackCount = stackCount;
                        GenPlace.TryPlaceThing(thing, pos, map, ThingPlaceMode.Near);
                    }
                }
            }

            //增加诅咒值
            if (map.GetComponent<MapComponent_Curse>() is MapComponent_Curse comp)
            {
                comp.AddTargetCurseValue(Props.curseValue);
            }

            //挖完移除坟墓
            parent.Destroy(DestroyMode.Vanish);
        }
    }
}
